-module(api_auth).

-export([
    login/1
    ,logout/1
    ,login_token/1
]).

-include("common.hrl").
-include("http.hrl").
-include("error.hrl").
-include("key.hrl").


%%%===================================================================
%%% API
%%%===================================================================

login(#{req := Req}) ->
    [Account, Password] = util_cowboy:must_post_val(Req, [<<"account">>, <<"password">>]),

    case model_adm_user:get_by_account(Account) of
        {ok, undefined} ->
            ?RESP_FAILED(?HTTP_STATUS_NOT_FOUND, ?ERROR_AU_NOT_EXIST);
        {ok, AdmUser = #{id := Id, password := DbPassword}} ->
            case util:md5(Password) of
                DbPassword ->
                    Token = token:make(Id),
                    AdmUser2 = model_adm_user:login_after(AdmUser),
                    ?RESP_SUCCESS(#{token => Token, user => dto:to_adm_user(AdmUser2)});
                _ ->
                    ?RESP_FAILED(?HTTP_STATUS_UNAUTHORIZED, ?ERROR_AU_PASSWORD_NOT_SAME)
            end;
        {error, Reason} ->
            ?ERR("MySQL 错误:~s", [Reason]),
            ?RESP_FAILED(?HTTP_STATUS_INTERNAL_SERVER_ERROR, ?ERROR_DB)
    end.

logout(#{req := Req}) ->
    case cowboy_req:header(?KEY_HTTP_HEADER_X_TOKEN, Req) of
        TokenBin when TokenBin =/= undefined andalso TokenBin =/= <<>> ->
            token:destroy(util_type:to_integer(TokenBin));
        _ ->
            ok
    end,
    ?RESP_SUCCESS(undefined).

login_token(_Req) ->
    AdmUser = erlang:get(?KEY_ADM_USER),
    AdmUser2 = model_adm_user:login_after(AdmUser),

    erlang:put(?KEY_ADM_USER, AdmUser2),

    ?RESP_SUCCESS(dto:to_adm_user(AdmUser2)).


%%%===================================================================
%%% Internal functions
%%%===================================================================
